import ffmpegPath from '@ffmpeg-installer/ffmpeg' // 安装 ffmpeg 的二进制文件
import ffprobePath from '@ffprobe-installer/ffprobe' // 安装 ffprobe 的二进制文件
import ffmpeg from 'fluent-ffmpeg' // 一个封装了 ffmpeg API 的库，当然可以选择不安装，直接使用字符串拼接的方式调用
import path, { dirname } from 'path'
import { existsSync, mkdirSync, renameSync } from 'fs'
import {
  OutputFormat,
  Resolution,
  Bitrate,
  Framerate,
  AudioQuality,
  VideoCodec
} from '../../renderer/src/enums/settingEnum'
import { BrowserWindow } from 'electron'

ffmpeg.setFfmpegPath(ffmpegPath.path.replace('app.asar', 'app.asar.unpacked')) // 修改
ffmpeg.setFfprobePath(ffprobePath.path.replace('app.asar', 'app.asar.unpacked')) // 修改

export interface FFmpegOptions {
  name: string
  inputPath: string
  outputPath: string
  format?: OutputFormat
  resolution?: Resolution
  bitrate?: Bitrate
  framerate?: Framerate
  audioQuality?: AudioQuality
  videoCodec?: VideoCodec
}

export default class FFmpeg {
  private ffmpeg: ffmpeg.FfmpegCommand
  private inputPath: string
  private outputPath: string
  private tempPath: string
  private saveFilePath: string
  private window: BrowserWindow

  constructor(options: FFmpegOptions, window: BrowserWindow) {
    this.ffmpeg = ffmpeg(options.inputPath)
    this.window = window
    this.inputPath = options.inputPath
    this.outputPath = options.outputPath
    this.tempPath = path.join(
      options.outputPath,
      `.temp_${Date.now()}_${options.name}.${options.format || 'mp4'}`
    )
    this.saveFilePath = path.join(
      options.outputPath,
      `${new Date().toISOString().slice(0, 10).replace(/-/g, '')}_${options.name}_${options.resolution}_${options.framerate}.${options.format || 'mp4'}`
    )

    // 设置默认值
    this.setOutputFormat(options.format || OutputFormat.MP4)
    this.setResolution(options.resolution || Resolution.FHD)
    this.setBitrate(options.bitrate || Bitrate.MEDIUM)
    this.setFramerate(options.framerate || Framerate.MEDIUM)
    this.setAudioQuality(options.audioQuality || AudioQuality.MEDIUM)
    this.setVideoCodec(options.videoCodec || VideoCodec.H264)
  }

  // 设置输出格式
  setOutputFormat(format: OutputFormat): this {
    this.ffmpeg.format(format)
    return this
  }

  // 设置分辨率
  setResolution(resolution: Resolution): this {
    const [width, height] = resolution.split('x')
    this.ffmpeg.size(`${width}x${height}`)
    return this
  }

  // 设置码率
  setBitrate(bitrate: Bitrate): this {
    this.ffmpeg.videoBitrate(bitrate)
    return this
  }

  // 设置帧率
  setFramerate(framerate: Framerate): this {
    this.ffmpeg.fps(Number(framerate))
    return this
  }

  // 设置音频质量
  setAudioQuality(audioQuality: AudioQuality): this {
    this.ffmpeg.audioBitrate(audioQuality)
    return this
  }

  // 设置视频编码器
  setVideoCodec(videoCodec: VideoCodec): this {
    this.ffmpeg.videoCodec(videoCodec)
    return this
  }

  public cancel(): string {
    if (this.ffmpeg) {
      this.ffmpeg.kill('SIGKILL')
      // 返回临时路径
    }
    return this.tempPath
  }

  public end() {
    // 将临时文件移动到最终输出路径
    renameSync(this.tempPath, this.saveFilePath)
    this.window.webContents.send('video:conversionComplete', {
      path: this.inputPath,
      success: true
    })
  }

  // 修改 process 方法以支持暂停
  public process(): Promise<void> {
    return new Promise((resolve, reject) => {
      // 检查输出目录是否存在，如果不存在则创建
      const outputDir = dirname(this.outputPath)
      if (!existsSync(outputDir)) {
        mkdirSync(outputDir, { recursive: true })
      }

      this.ffmpeg
        .on('progress', (progress) => {
          // 发送进度事件到渲染进程
          this.window.webContents.send('video:progress', {
            percent: Math.floor(progress.percent!),
            frames: progress.frames,
            currentFps: progress.currentFps,
            currentKbps: progress.currentKbps,
            path: this.inputPath
          })
        })
        .on('end', () => {
          this.end()
          resolve()
        })
        .on('error', (err) => reject(err))
        .save(this.tempPath)
    })
  }
}
